package network;

import com.mongodb.MongoClient;
import data.DatabaseClient;
import event.EventBase;
import event.EventEnum;
import event.EventSystem;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SshConnection extends ConnectionBase implements event.ListenerInterface {
    private Session session;
    private SshConnectionConfig config;

    public SshConnection(SshConnectionConfig config) {
        session = null;
        this.config = config;
    }

    @Override
    public DatabaseClient connect() {
        MongoClient mongoClient = null;
        try {
            java.util.Properties properties = new java.util.Properties();
            properties.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            session = jsch.getSession(config.getSshUser(), config.getSshHost(), config.getSshPort());
            session.setPassword(config.getSshPassword());
            session.setConfig(properties);
            session.connect();
            session.setPortForwardingL(config.getLocalPort(), config.getRemoteHost(), config.getRemotePort());
            mongoClient = new MongoClient(config.getLocalHost(), config.getLocalPort());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            EventSystem.instance().on(EventEnum.stageClose, this);
        }

        DatabaseClient databaseClient = new DatabaseClient(config.getDatabaseName(), config.getRemoteHost(), config.getRemotePort().toString());
        databaseClient.setClient(mongoClient);
        return databaseClient;
    }

    @Override
    public void close() {
        try {
            if (session != null) {
                session.delPortForwardingL(config.getLocalPort());
            }
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    @Override
    public void process(EventBase event) {
        if (event.getName().equals(EventEnum.stageClose)) {
            try {
                close();
            }
            catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }
}
